package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.config.ExThreadExtetns;
import com.itheima.entity.AddressBook;
import com.itheima.result.R;
import com.itheima.service.AddressBookService;
import com.itheima.service.OrderService;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
@Slf4j
public class addressBookController {
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping
    public R addRess(@RequestBody AddressBook addressBook) {
        Long globalThread = ExThreadExtetns.getGlobalThread();
        addressBook.setUserId(globalThread);
        addressBookService.save(addressBook);
        return R.success("添加成功");
    }

    @GetMapping("/list")
    public R getResById() {
        Long globalThread = ExThreadExtetns.getGlobalThread();
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId, globalThread);
        List<AddressBook> list = addressBookService.list(lqw);
        return R.success(list);
    }

    @PutMapping("/default")
    public R putDefult(@RequestBody AddressBook addressBook) {
        log.info("addressBook:{}", addressBook);
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getUserId, ExThreadExtetns.getGlobalThread());
        wrapper.set(AddressBook::getIsDefault, 0);
        //SQL:update address_book set is_default = 0 where user_id = ?
        addressBookService.update(wrapper);

        addressBook.setIsDefault(1);
        //SQL:update address_book set is_default = 1 where id = ?
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }

    @GetMapping("/default")
    public R getBuyShopping() {
        Long globalThread = ExThreadExtetns.getGlobalThread();
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId, globalThread);
        lqw.eq(AddressBook::getIsDefault, 1);
        AddressBook one = addressBookService.getOne(lqw);
        return R.success(one);

    }
}
